package models

import (
	"gitee.com/sansaniot/ssiot-core/facade/runtime"
)

type UserRole struct {
	RoleId string `json:"roleId" gorm:"type:varchar(50);comment:角色ID"`
	UserId string `json:"userId" gorm:"type:varchar(50);comment:用户ID"`
	//model.Model
	CRUD `json:"-" gorm:"-"`
}

type RoleInfo struct {
	RoleName string `json:"roleName"`
	RoleId   string `json:"roleId"`
}

func (UserRole) TableName() string {
	return "sys_user_role_r"
}

func (u UserRole) GetRoleInfoByUserId(userId string) RoleInfo {
	db := runtime.Runtime.GetDbByKey("db")
	roleInfo := RoleInfo{}

	_ = db.Table("sys_user_role_r ur").Joins("left join sys_role role on ur.role_id = role.id").
		Select("ur.role_id, role.role_name").
		Where("ur.user_id = ?", userId).
		Scan(&roleInfo).Error

	return roleInfo
}

func (u UserRole) GetUserIdsByRoleId(roleId string) []string {
	db := runtime.Runtime.GetDbByKey("db")
	userIds := make([]string, 0)
	_ = db.Table("sys_user_role_r ur").
		Select("ur.user_id ").
		Where("ur.role_id = ?", roleId).
		Find(&userIds).Error
	return userIds
}
